﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using GalaSoft.MvvmLight;
using System.ComponentModel;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System.Windows;
using HIWSystem.Common;
using HIWSystem.Models;
using HIWSystem.Helpers;
using System.Data;
using System.Collections.ObjectModel;

namespace HIWSystem.ViewModel
{
    [MetadataType(typeof(AddEmployeeViewModel))]
    public class AddEmployeeViewModel : ViewModelBase, IDataErrorInfo
    {
        public AddEmployeeViewModel()
        {
            Messenger.Default.Register<string>(this, "CompleteEmployeeUpdate", LoadAllEmployeeInfoAsync);
        }
        #region 属性
        /// <summary>
        /// 表单验证错误集合
        /// </summary>
        private Dictionary<String, String> dataErrors = new Dictionary<String, String>();

        private string userNo;
        /// <summary>
        /// 工号
        /// </summary>
        //[Required]
        //[StringLength(maximumLength:8,MinimumLength =8,ErrorMessage ="工号的长度为8位")]
        [RegularExpression(@"^(HIW|TEM|TS)\d{5}$",ErrorMessage ="输入的工号格式不正确,正确的格式(HIW|TEM|TS+5位数字)")]
        public string UserNo
        {
            get { return userNo; }
            set { userNo = value; this.RaisePropertyChanged(() => UserNo); }
        }
        private string nameCn;
        /// <summary>
        /// 中文名
        /// </summary>
        [Required]
        public string NameCn
        {
            get { return nameCn; }
            set { nameCn = value; this.RaisePropertyChanged(() => NameCn); }
        }
        private string nameEn;
        /// <summary>
        /// 英文名
        /// </summary>
        [RegularExpression(@"[a-zA-Z]*")]
        public string NameEn
        {
            get { return nameEn; }
            set { nameEn = value; this.RaisePropertyChanged(() => NameEn); }
        }
        private string password;
        /// <summary>
        /// 密码
        /// </summary>
        [Required]
        public string Password
        {
            get { return password; }
            set { password = value; this.RaisePropertyChanged(() => Password); }
        }
        private string sex;
        /// <summary>
        /// 性别
        /// </summary>
        [RegularExpression("(男|女)",ErrorMessage ="性别只能是男或者女")]
        public string Sex
        {
            get { return sex; }
            set { sex = value; this.RaisePropertyChanged(() => Sex); }
        }
        
        private string departmentNo;
        /// <summary>
        /// 部门编号
        /// </summary>
        public string DepartmentNo
        {
            get { return departmentNo; }
            set { departmentNo = value; this.RaisePropertyChanged(() => DepartmentNo); }
        }
        private string telephone;
        /// <summary>
        /// 电话号码
        /// </summary>
        [RegularExpression(@"^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$")]
        public string Telephone
        {
            get { return telephone; }
            set { telephone = value; this.RaisePropertyChanged(() => Telephone); }
        }
        //private String userEmail;
        ///// <summary>
        ///// 用户邮件
        ///// </summary>
        //[Required]
        //[StringLength(100, MinimumLength = 2)]
        //[RegularExpression("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$", ErrorMessage = "请填写正确的邮箱地址.")]
        //public String UserEmail
        //{
        //    get { return userEmail; }
        //    set { userEmail = value; }
        //}
        private string address;
        /// <summary>
        /// 地址
        /// </summary>
        public string Address
        {
            get { return address; }
            set { address = value; this.RaisePropertyChanged(() => Address); }
        }
        private string oldUserNo;
        /// <summary>
        /// 旧工号
        /// </summary>
        public string OldUserNo
        {
            get { return oldUserNo; }
            set { oldUserNo = value; this.RaisePropertyChanged(() => OldUserNo); }
        }
        private string access;
        /// <summary>
        /// 权限
        /// </summary>
        [RegularExpression(@"^[A-Z]{2}(\|[A-Z]{2})*$",ErrorMessage ="权限的格式不正确(例如:AB|AC|AD)")]
        public string Access
        {
            get { return access; }
            set { access = value; this.RaisePropertyChanged(() => Access); }
        }
        private ObservableCollection<EmployeesEntity> employeeResource;
        /// <summary>
        /// 数据网格员工数据实体源
        /// </summary>
        public ObservableCollection<EmployeesEntity> EmployeeResource
        {
            get { return employeeResource; }
            set { employeeResource = value; this.RaisePropertyChanged(() => EmployeeResource); }
        }
        #endregion


        #region 命令
        private RelayCommand loadPageCmd;
        /// <summary>
        /// 页面加载命令
        /// </summary>
        public RelayCommand LoadPageCmd
        {
            get 
            {
                if (loadPageCmd==null)
                {
                    loadPageCmd = new RelayCommand(LoadedPage);
                }
                return loadPageCmd; 
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand unloadedPageCmd;

        public RelayCommand UnloadedPageCmd
        {
            get 
            {
                if (unloadedPageCmd==null)
                {
                    unloadedPageCmd = new RelayCommand(UnloadedPage);
                }
                return unloadedPageCmd; 
            }
            set { unloadedPageCmd = value; }
        }


        private RelayCommand submitCmd;
        /// <summary>
        /// 提交表单命令
        /// </summary>
        public RelayCommand SubmitCmd
        {
            get
            {
                if (submitCmd == null)
                    return new RelayCommand(() => SubmitForm());
                return submitCmd;
            }
            set { submitCmd = value; }
        }
        private RelayCommand<EmployeesEntity> updateEmployeeCmd;
        /// <summary>
        /// 更新员工信息命令
        /// </summary>
        public RelayCommand<EmployeesEntity> UpdateEmployeeCmd
        {
            get 
            {
                if (updateEmployeeCmd==null)
                {
                    updateEmployeeCmd = new RelayCommand<EmployeesEntity>(UpdateEmployee);
                }
                return updateEmployeeCmd;
            }
            set { updateEmployeeCmd = value; }
        }
        private RelayCommand<EmployeesEntity> deleteEmployeeCmd;

        public RelayCommand<EmployeesEntity> DeleteEmployeeCmd
        {
            get 
            {
                if (deleteEmployeeCmd==null)
                {
                    deleteEmployeeCmd = new RelayCommand<EmployeesEntity>(DeleteEmployee);
                }
                return deleteEmployeeCmd;
            }
            set { deleteEmployeeCmd = value; }
        }

        /// <summary>
        /// 提交表单
        /// </summary>
        private void SubmitForm()
        {
            if (dataErrors.Count == 0)
            {
                string retMsg = string.Empty;
                DataTable dtEmp = new DataTable();
                EmployeesEntity employeesEntity = new EmployeesEntity()
                {
                    UserNo = this.UserNo.ToUpper()??"",
                    NameCn = this.NameCn??"",
                    NameEn=this.NameEn??"",
                    Password=MD5Helper.MD5Encrypt(this.Password),
                    Sex=this.Sex??"",
                    DepartmentNo=this.DepartmentNo??"",
                    Telephone=this.Telephone??"",
                    Address=this.Address??"",
                    OldUserNo=this.OldUserNo??"",
                    Access=this.Access??""
                };
                retMsg = BusinessProcess.AddEmployees(employeesEntity, out dtEmp);
                if (retMsg.Split('|')[0] == "OK")
                {
                    EmployeeResource = new ObservableCollection<EmployeesEntity>();
                    for (int i = 0; i < dtEmp.Rows.Count; i++)
                    {
                        EmployeeResource.Add(
                            new EmployeesEntity
                            {
                                UserNo = dtEmp.Rows[i]["UserNo"].ToString(),
                                NameCn = dtEmp.Rows[i]["NameCn"].ToString(),
                                NameEn = dtEmp.Rows[i]["NameEn"].ToString(),
                                Password = dtEmp.Rows[i]["Password"].ToString(),
                                Sex = dtEmp.Rows[i]["Sex"].ToString(),
                                DepartmentNo = dtEmp.Rows[i]["DepartmentNo"].ToString(),
                                Telephone = dtEmp.Rows[i]["Telephone"].ToString(),
                                Address = dtEmp.Rows[i]["Address"].ToString(),
                                OldUserNo = dtEmp.Rows[i]["OldUserNo"].ToString(),
                                Access = dtEmp.Rows[i]["Access"].ToString(),
                                CreateAt = dtEmp.Rows[i]["CreateAt"].ToString(),
                            });
                    }
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            } /*MessageBox.Show("验证通过！");*/
            else 
                MessageBox.Show("信息输入有误！","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Error);
        }
        private RelayCommand searchLevelCmd;

        public RelayCommand SearchLevelCmd
        {
            get 
            {
                if (searchLevelCmd==null)
                {
                    searchLevelCmd = new RelayCommand(()=> {
                        ViewManager.Show("MenuLevel");
                    });
                }
                return searchLevelCmd; 
            }
            set { searchLevelCmd = value; }
        }

        #endregion




        #region 附属方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            LoadAllEmployeeInfoAsync("");
        }
        /// <summary>
        /// 卸载页面
        /// </summary>
        private void UnloadedPage()
        {
            Messenger.Default.Unregister(this);
        }
        /// <summary>
        /// 异步加载所有员工信息
        /// </summary>
        private async void LoadAllEmployeeInfoAsync(string msg)
        {
            DataTable dtEmployee = new DataTable();
            dtEmployee = BusinessProcess.GetAllEmployeeInfo();
            EmployeeResource = new ObservableCollection<EmployeesEntity>();
            ObservableCollection<EmployeesEntity> tmpEmployeeInfo = new ObservableCollection<EmployeesEntity>();
            await Task.Run(() => 
            {
                for (int i = 0; i < dtEmployee.Rows.Count; i++)
                {
                    tmpEmployeeInfo.Add(new EmployeesEntity {
                        UserNo = dtEmployee.Rows[i]["UserNo"].ToString(),
                        NameCn = dtEmployee.Rows[i]["NameCn"].ToString(),
                        NameEn = dtEmployee.Rows[i]["NameEn"].ToString(),
                        Password=dtEmployee.Rows[i]["Password"].ToString(),
                        Sex = dtEmployee.Rows[i]["Sex"].ToString(),
                        DepartmentNo = dtEmployee.Rows[i]["DepartmentNo"].ToString(),
                        Telephone = dtEmployee.Rows[i]["Telephone"].ToString(),
                        Address = dtEmployee.Rows[i]["Address"].ToString(),
                        OldUserNo = dtEmployee.Rows[i]["OldUserNo"].ToString(),
                        Access = dtEmployee.Rows[i]["Access"].ToString(),
                        CreateAt = dtEmployee.Rows[i]["CreateAt"].ToString(),
                    });
                }
                Application.Current.Dispatcher.BeginInvoke((Action)(() => {
                    EmployeeResource = tmpEmployeeInfo;
                }));
            });
            //表示从子窗口(更新界面)传过来的参数，表示需要关闭子窗口
            if (msg!="")
            {
                ViewManager.Close("UpdateEmployee");
            }
        }
        /// <summary>
        /// 更新员工信息
        /// </summary>
        /// <param name="obj">员工实体类</param>
        private void UpdateEmployee(EmployeesEntity obj)
        {
            string retMsg = string.Empty;//返回的状态信息
            string[] arrayMsg = new string[2];
            if (obj!=null)
            {
                retMsg = BusinessProcess.EmployeeIsHaveModuleAuthority("AA");
                arrayMsg = retMsg.Split('|');
                //Y表示有权限
                if (arrayMsg[0] == "Y")
                {
                    ViewManager.Show("UpdateEmployee");
                    Messenger.Default.Send<EmployeesEntity>(obj, "UpdateEmployeeInfo");
                }
                else
                {
                    MessageBox.Show(arrayMsg[1],"软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Warning);
                }
            }
        }
        /// <summary>
        /// 删除员工信息
        /// </summary>
        /// <param name="obj">员工实体类</param>
        private void DeleteEmployee(EmployeesEntity obj)
        {
            string retMsg = string.Empty;//返回的状态信息
            string[] arrayMsg = new string[2];
            if (obj!=null)
            {
                retMsg = BusinessProcess.EmployeeIsHaveModuleAuthority("AB");
                arrayMsg = retMsg.Split('|');
                //Y表示有权限
                if (arrayMsg[0]=="Y")
                {
                    //确定用户是否要删除，防止误删
                    MessageBoxResult boxResult= MessageBox.Show(string.Format("确定要删除工号【{0}】吗？",obj.UserNo),"软件温馨提示!",MessageBoxButton.YesNo,MessageBoxImage.Question);
                    if (boxResult==MessageBoxResult.Yes)
                    {
                        if (BusinessProcess.DeleteEmployeeInfo(obj))
                        {
                            EmployeeResource.Remove(obj);
                        }
                        else
                        {
                            MessageBox.Show("删除失败", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
                else 
                {
                    MessageBox.Show(arrayMsg[1], "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        public string this[string columnName]
        {
            get
            {
                ValidationContext vc = new ValidationContext(this, null, null);
                vc.MemberName = columnName;
                var res = new List<ValidationResult>();
                var result = Validator.TryValidateProperty(this.GetType().GetProperty(columnName).GetValue(this, null), vc, res);
                if (res.Count > 0)
                {
                    AddDic(dataErrors, vc.MemberName);
                    return string.Join(Environment.NewLine, res.Select(r => r.ErrorMessage).ToArray());
                }
                RemoveDic(dataErrors, vc.MemberName);
                return null;
            }
        }

        public string Error
        {
            get
            {
                return null;
            }
        }
        /// <summary>
        /// 移除字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void RemoveDic(Dictionary<String, String> dics, String dicKey)
        {
            dics.Remove(dicKey);
        }

        /// <summary>
        /// 添加字典
        /// </summary>
        /// <param name="dics"></param>
        /// <param name="dicKey"></param>
        private void AddDic(Dictionary<String, String> dics, String dicKey)
        {
            if (!dics.ContainsKey(dicKey)) dics.Add(dicKey, "");
        }
        #endregion
    }
}
